import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { userInfoApi } from "../api/user";

export interface UserInfo {
    uid: number,
    username: string,
    profile: string,
    registerTime: string
}

export const userStore = defineStore('userStore', {
    state: () => {
        return {
            user: reactive<UserInfo>({
                uid: 0,
                username: '',
                profile: '',
                registerTime: ''
            }),
            token: reactive<String>(''),
            loading: ref(false)
        }
    },
    actions: {
        setToken(token: string) {
            this.token = token
        },
        setUser(user: UserInfo) {
            this.user = user
        },
        clearUser() {
            this.user = reactive<UserInfo>({
                uid: 0,
                username: '',
                profile: '',
                registerTime: ''
            })
        },
        setLoading(loading: boolean) {
            this.loading = loading
        },
        refreshUserInfo() {
            this.loading = true
            userInfoApi().then((e) => {
                this.setUser(e.data)
                this.loading = !this.loading
            })
        }
    },
    getters: {
        isLogin: state => !!(state.token && state.token.length > 0),
        tokenVal: state => state.token,
        isLoading: state => state.loading
    },
    persist: true
})